package org.example.journal_items.controller;

import org.example.journal_items.entityDTO.StatsDTO;
import org.example.journal_items.Entity.User;
import org.example.journal_items.service.StatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.example.journal_items.security.CustomUserDetails;

@RestController
@RequestMapping("/stats")
public class StatsController {

  @Autowired
  private StatsService statsService;

  @GetMapping("/homepage")
  public ResponseEntity<StatsDTO> getHomepageStats(@AuthenticationPrincipal CustomUserDetails userDetails) {
    try {
      if (userDetails == null || userDetails.getUser() == null) {
        throw new RuntimeException("用户未认证");
      }

      Long userId = userDetails.getUser().getId();

      StatsDTO stats = statsService.getHomepageStats(userId);

      return ResponseEntity.ok(stats);

    } catch (Exception e) {
      throw new RuntimeException("获取统计数据失败: " + e.getMessage(), e);
    }
  }

  @GetMapping("/test")
  public ResponseEntity<String> testStats() {
    try {
      return ResponseEntity.ok("统计接口正常工作");
    } catch (Exception e) {
      return ResponseEntity.status(500).body("统计接口测试失败: " + e.getMessage());
    }
  }

  @GetMapping("/simple")
  public ResponseEntity<StatsDTO> getSimpleStats(@AuthenticationPrincipal CustomUserDetails userDetails) {
    try {
      if (userDetails == null || userDetails.getUser() == null) {
        throw new RuntimeException("用户未认证");
      }

      Long userId = userDetails.getUser().getId();

      // 返回硬编码的测试数据
      StatsDTO stats = new StatsDTO();
      stats.setTotalDiaries(10);
      stats.setCompletedTodos(5);
      stats.setFavoriteDiaries(3);
      stats.setConsecutiveDays(2);

      return ResponseEntity.ok(stats);

    } catch (Exception e) {
      throw new RuntimeException("获取简单统计数据失败: " + e.getMessage(), e);
    }
  }
}